﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.ComponentModel;
using Doo.Controls;
using Doo.Scripts;
using Doo.WebUI;

namespace Doo.DataView
{
    public class DataViewClientEvents : Doo.Scripts.ClientEvents
    {
        /// <summary>
        /// 获取数据之前触发事件
        /// </summary>
        [Doo.WebUI.ClientEvent("datafetching")]
        public ClientEvent DataFetching { get; set; }

        /// <summary>
        /// 获取到数据时触发事件
        /// </summary>
        [Doo.WebUI.ClientEvent("databinding")]
        public ClientEvent DataBinding { get; set; }

        /// <summary>
        /// 数据已经绑定时触发事件
        /// </summary>
        [Doo.WebUI.ClientEvent("databound")]
        public ClientEvent DataBound { get; set; }
        
    }

    /// <summary>
    /// 数据源的基类
    /// 数据浏览者
    /// </summary>
    public abstract class DataViewBase : DooControl
    {
        const string _ScriptName = "Doo.WebUI.DataView.script.js";
        
        /// <summary>
        /// 设置数据源的ID
        /// </summary>
        [IDReferenceProperty(typeof(Doo.DataSource.DataSourceBase))]
        public string DataSourceID { get; set; }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        public Doo.Template.TemplateEvents TemplateEvents { get; set; }

        /// <summary>
        /// 设置分页控件的ID
        /// </summary>
        [IDReferenceProperty(typeof(Doo.Controls.Pager))]
        public string PagerID { get; set; }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (this.TemplateEvents != null) this.TemplateEvents.Init(Page, Parent);
        }

        protected override void SetScriptDescriptor(ScriptControlDescriptor descriptor)
        {
            base.SetScriptDescriptor(descriptor);

            if (!string.IsNullOrEmpty(DataSourceID))
            {
                var ctl = Parent.FindControl(DataSourceID);
                descriptor.AddProperty("datasourceid", ctl.ClientID);
            }
            if (!string.IsNullOrEmpty(PagerID))
            {
                var ctl = Parent.FindControl(PagerID);
                descriptor.AddProperty("pagerid", ctl.ClientID);
            }
            if (this.TemplateEvents != null && this.TemplateEvents.Count > 0)
            {
                descriptor.AddProperty("inittplevents", this.TemplateEvents.ToHashtable());
            }
        }

        protected override void SetScriptReferences(List<ScriptReference> reference)
        {
            base.SetScriptReferences(reference);

            reference.Add(new ScriptReference(_ScriptName, this.GetType().Assembly.FullName));
        }
    }
}
